package com.duing.controller;


import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.duing.common.PageResult;
import com.duing.common.ResponseResult;
import com.duing.dto.AuthorQueryDTO;
import com.duing.entity.Author;
import com.duing.enums.ErrorCode;
import com.duing.service.impl.AuthorServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;

@RestController
@RequestMapping("/api/author")
public class AuthorController {
  @Autowired
  private AuthorServiceImpl authorService;
  @PostMapping("/add")
  public ResponseResult<Author> addAuthor(@Valid Author author) {
    authorService.validateAuthor(author);
    authorService.save(author);
    return ResponseResult.success(author);
  }

  @PostMapping("/delete")
  public ResponseResult<Boolean> deleteAuthor(@RequestParam Long id) {
    boolean result = authorService.removeById(id);
    return result ? ResponseResult.success(result) : ResponseResult.error(ErrorCode.NOT_FOUND.getCode(), "作者不存在");
  }

  @PostMapping("/update")
  public ResponseResult<Author> updateAuthor(@Valid Author author) {
    authorService.updateById(author);
    return ResponseResult.success(author);
  }


  @GetMapping("/listByParams")
  public ResponseResult<PageResult<Author>> getAuthorsByKeyword(
          @RequestParam(defaultValue = "0") int page,
          @RequestParam(defaultValue = "10") int size,
          @ModelAttribute AuthorQueryDTO dto
  ) {
      Page<Author> authorPage = authorService.getAuthorsByKeyword(page, size, dto);
      PageResult<Author> pageResult = new PageResult<>(authorPage.getRecords(),authorPage.getTotal(),authorPage.getCurrent(),authorPage.getSize());
      return ResponseResult.success(pageResult);
  }

  @GetMapping("/{id}")
  public ResponseResult<Author> getAuthorById(@PathVariable Long id) {
    Author author = authorService.getById(id);
    return author != null ? ResponseResult.success(author) : ResponseResult.error(ErrorCode.NOT_FOUND.getCode(), "作者不存在");
  }
}
